package cn.sytton.taffecloud.common.servlet.filter;

import cn.sytton.taffecloud.common.base.properties.TokenProperties;
import cn.sytton.taffecloud.common.base.util.JwtUtil;
import cn.sytton.taffecloud.common.base.security.LoginUser;
import cn.sytton.taffecloud.common.base.util.SecurityUtil;
import cn.sytton.taffecloud.common.base.util.SpringContextUtil;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Token过滤器,应用于所有微服务模块, 从Token获取登录用户
 *
 * @author skyrock
 */
public class TokenFilter implements Filter {

    private JwtUtil jwtUtil;
    private TokenProperties tokenProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        jwtUtil = SpringContextUtil.getBean("jwtUtil");
        tokenProperties = SpringContextUtil.getBean("tokenProperties");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = ((HttpServletRequest)request).getHeader(tokenProperties.getHeader());
        if (StringUtils.hasText(token)) {
            LoginUser loginUser = jwtUtil.getLoginUser(token);
            SecurityUtil.setLoginUser(loginUser);
        }
        chain.doFilter(request, response);
    }
}
